package com.ituzhi.mqtt.controller;

import com.alibaba.fastjson2.JSON;
import com.ituzhi.mqtt.server.config.MqttConfigurationProperties;
import com.ituzhi.mqtt.server.service.MqttMessageSender;
import com.ituzhi.mqtt.server.service.MqttMessageSubscriber;
import jakarta.annotation.Resource;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * packageName com.ituzhi.mqtt.controller
 *
 * @author 死道友不死贫道
 * @version JDK 17
 * @className TestController
 * @date 2025-01-22
 * @description TODO
 */
@RestController
@RequestMapping("/mqtt")
public class TestController {



    @Resource
    private MqttMessageSender mqttMessageSender;
    @Resource
    private MqttMessageSubscriber mqttMessageSubscriber;
    @Resource
    private MqttConfigurationProperties mqttConfigurationProperties;

    /**
     * 发送消息
     */
    @GetMapping(value = "/hello")
    public String sayHello() {
        String DEFAULT_TOPIC = mqttConfigurationProperties.getSubTopic().split(",")[0]; // topic/test
        String msg = "hello mqtt-springboot";
        mqttMessageSender.sendMessage(DEFAULT_TOPIC, msg);
        return "发送消息".concat(msg);
    }

    /**
     * 发送消息
     * 画板初始化的时候调用接口初始化画布数据
     */
    @GetMapping(value = "/send-msg")
    public Object sendMsg(@RequestBody Map<String,Object> param) {
        Map<String,Object> Re = new HashMap<>();
        String topic = param.get("topic").toString();
        Object object = param.get("msg");
        String jsonString = JSON.toJSONString(object);
        mqttMessageSender.sendMessage(topic, jsonString);
        Re.put("data","发送成功");
        return Re;
    }

    /**
     * 发送消息
     * @param qos 0,1,2
     */
    @GetMapping(value = "/send-msg/qos")
    public String sendMsg(@RequestParam String topic, @RequestParam Integer qos, @RequestParam String msg) {
        mqttMessageSender.sendMessage(topic, qos, msg);
        return "发送消息".concat(msg);
    }

    /**
     * 添加订阅
     */
    @GetMapping(value = "/subscribe")
    public String subscribeTopic(@RequestParam String topic) {
        return mqttMessageSubscriber.subscribeTopic(topic);
    }


}